const mongodb =  require('mongodb');
const { MongoClient, ObjectId } = mongodb;

const dbUrl = 'mongodb://localhost:27017';
let db;
async function getMusicDB() {
    return new Promise(function (resolve, reject) {
        if (db) {
            process.nextTick(function () {
                resolve(db);
            });
            return;
        }
        MongoClient.connect(dbUrl, { useNewUrlParser: true }, function (err, client) {
            if (err) {
                reject(err);
                return;
            }
            db = client.db('MusicDB');
            resolve(db);
        });
    })
}

async function createSinger(singer) {
    const database = await getMusicDB();
    const collection = database.collection('singer');
    return new Promise(function (resolve, reject) {
        collection.insertOne(singer, function (err, result) {
            if (err) {
                return reject(err);
            }
            resolve(result)
        })
    });
}

async function editSinger(_id, singer) {
    const database = await getMusicDB();
    const collection = database.collection('singer');
    return new Promise(function (resolve, reject) {
        collection.updateOne({_id: _id}, {$set: singer}, function (err, result) {
            if (err) {
                return reject(err);
            }
            resolve(result)
        })
    });
}

async function querySingers(name, type, detail) {
    const database = await getMusicDB();
    const collection = database.collection('singer');
    return new Promise(function (resolve, reject) {
        collection.find({
            $or: [
                {name: new RegExp(name)},
                {type: new RegExp(name)}
            ]
        }).toArray(function (err, result) {
            if (err) {
                return reject(err);
            }
            resolve(result)
        });
    });
}

module.exports = {
    getSingers,
    querySingers,
    createSinger,
    editSinger
};